package com.gxa.community.agent.utils;

import com.gxa.community.core.utils.R;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * 作者： Juran on 2022-07-12 16:55
 * 作者博客：iit.la
 */
public class RestUtil {
    private static RestTemplate restTemplate ;

    static{
        // OkHttp3ClientHttp性能比较好, 需要引入jar
        // restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        restTemplate = new RestTemplate();
    }

    /**
     *
     * @param url
     * @param headers 自定义请求头,null表示没有需要传递的请求头
     * @return
     */
    public static R postWithParams(String url, Map<String,String> headers, MultiValueMap params){

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        if(headers != null){
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(),entry.getValue());
            }
        }
        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);
        // 通过post方式发送请求的方法
        R result = restTemplate.postForObject(url, httpEntity, R.class);

        return result;
    }


    public static R postWithParams(String url, MultiValueMap params){
        return postWithParams(url, null, params);
    }

}
